import {
	imgcdn,
	staticUrl,
	domain
} from './config.js'
import {
	useMainStore
} from '@/stores/index.js'
const mainStore = useMainStore()
export const Back = (delta = 1) => {
	uni.navigateBack({
		delta
	})
}

export const toUrl = (url) => {
	uni.navigateTo({
		url
	})
}

export const toRect = (url) => {
	if (!url) return Toast('未配置路径')
	uni.redirectTo({
		url
	})
}

export const toHome = () => {
	uni.redirectTo({
		url: '/pages/index/index'
	})
}



export const toLogin = () => {
	uni.navigateTo({
		url: '/pages/login/login'
	})
}

export const BarTitle = (title) => {
	uni.setNavigationBarTitle({
		title
	})
}

export const imgUrls = (imgs) => {
	const reg = /^(http|https)/;
	if (!imgs) return '';
	if (reg.test(imgs)) return imgs;
	if (typeof imgcdn === 'string') return `${imgcdn}${imgs}`;
	return '';
}

export const staticImg = (imgs) => {
	return staticUrl + imgs
}

export const Toast = (title, state = 1, duration = 1500, url = '') => {
	const showToast = {
		title,
		duration,
		icon: 'none',
		mask: false,
	}
	switch (state) {
		case 1:
			break;
		case 2:
			showToast.mask = true;
			showToast.success = () => {
				setTimeout(() => {
					Back()
				}, 800)
			}
			break;
		case 3:
			showToast.mask = true;
			showToast.success = () => {
				uni.redirectTo({
					url
				});
			}
			break;
	}
	uni.showToast(showToast);
}

export const showLoading = (msg = '') => {
	uni.showLoading({
		title: msg,
		mask: true,
	})
}
export const hideLoading = () => {
	uni.hideLoading();
}

export const chooseImage = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				console.log(res, 'res');
				const imgUrl = res.tempFiles[0];
				resolve(imgUrl)
			},
			fail: (err) => {
				console.log(err);
			}
		})
	})
}

// 上传文件
export const uploadFile = (file) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: domain + '/api/uploadFile',
			filePath: file,
			name: 'file',
			dataType: "json",
			header: {
				'token': mainStore.token
			},
			success: (uploadFileRes) => {
				const result = JSON.parse(uploadFileRes.data)
				if (result.code != 0) return Toast(result.msg);
				resolve(result.savePath);
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}





// 上传合同
export const uploadContract = (file) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: domain + '/contract/contractUpload',
			filePath: file,
			name: 'file',
			dataType: "json",
			header: {
				'token': mainStore.token
			},
			success: (uploadFileRes) => {
				const result = JSON.parse(uploadFileRes.data)
				if (result.code != 0) return Toast(result.msg);
				console.log(result, 'result');
				resolve(result.savePath);
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}


export const pageScroll = (scrollTop = 0, duration = 0) => {
	uni.pageScrollTo({
		scrollTop,
		duration
	})
}

export const Location = () => {
	return new Promise(resolve => {
		// #ifdef MP-WEIXIN
		wx.getFuzzyLocation({
			type: 'wgs84',
			success(res) {
				mainStore.position = res
				resolve(res)
			},
			fail(err) {
				console.log(err, 'err');
			}
		})
		// #endif
		// #ifndef MP-WEIXIN
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				mainStore.position = res
				resolve(res)
			},
			fail: (err) => {
				console.log(err, 'err');
			}
		})
		// #endif
	})
}


export const Call = (phone) => {
	if (!phone) return Toast('很抱歉，暂未配置联系电话！')
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

export const tampToDate = (timestamp, formatter = false) => {
	const date = new Date(Number(timestamp));
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return formatter ? `${year}年${month}月${day}日` : `${year}-${month}-${day}`

}


export const formatter = (type, value) => {
	if (type === 'year') {
		return `${value}年`;
	}
	if (type === 'month') {
		return `${value}月`;
	}
	if (type === 'day') {
		return `${value}日`;
	}
	return value;
}




export const validatePhone = (phoneNumber) => {
	const phoneRegex = /^1[3-9]\d{9}$/;
	return phoneRegex.test(phoneNumber);
}

export const Modal = (content = "", title = "提示", showCancel = true, cancelText = "取消") => {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title,
			content,
			cancelText,
			showCancel,
			cancelColor: '#cccccc',
			confirmColor: mainStore.color,
			success(res) {
				resolve(res.confirm)
			},
			fail(err) {
				reject(err)
			}
		})
	})

}

export const Logout = () => {
	mainStore.token = '';
	uni.reLaunch({
		url: '/pages/index/index'
	})
}

export const downFile = (url) => {
	showLoading('');
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			success: (res) => {
				const filePath = res.tempFilePath;
				resolve(filePath)
				// saveFile(filePath)
			},
			complete: () => {
				hideLoading();
			}
		})
	})
}

export const openDocument = (filePath) => {
	uni.openDocument({
		filePath,
		showMenu: true,
		success: (res) => {
			console.log('打开文档成功');
		},
		fail: (err) => {
			console.log(err, '打开文档失败');
		}
	})
}

export const saveFile = (tempFilePath) => {
	uni.saveFile({
		tempFilePath,
		success: (res) => {
			console.log(res);
			Toast('下载成功：文件保存')
		},
		fail: (err) => {
			Toast('下载失败')
		}
	})
}

export const openFile = (filePath) => {
	uni.openDocument({
		filePath,
		success: (res) => {
			console.log(res);
		},
		fail: (err) => {
			console.log(err);
		}
	})
}


export const getFileExtension = (filePath) => {
	if (!filePath || typeof filePath !== 'string') return '';
	filePath = filePath.trim();
	const lastDotIndex = filePath.lastIndexOf('.');
	const lastSeparatorIndex = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/'));
	if (lastDotIndex <= lastSeparatorIndex || lastDotIndex < 0) return '';
	const extension = filePath.substring(lastDotIndex + 1).toLowerCase();
	const extensionToImageMap = {
		pdf: 'pdf.png',
		docx: 'docx.png',
		doc: 'docx.png',
		ppt: 'ppt.png',
		jpg: 'jpg.png',
		png: 'png.png',
		md: 'md.png'
	};
	return extensionToImageMap[extension] || 'file.png';
};


export const previewImage = (fileImg) => {
	if (!fileImg) return;
	let arrImg = [];

	if (typeof fileImg == 'string') {
		fileImg.includes('http') ? arrImg.push(fileImg) : arrImg.push(imgcdn + fileImg)
	} else {
		for (let i in fileImg) {
			fileImg[i].includes('http') ? arrImg.push(fileImg[i]) : arrImg.push(imgcdn + fileImg[i])
		}
	}
	uni.previewImage({
		current: 0,
		urls: arrImg,
		indicator: "number",
		loop: true
	})
}


export const chooseMessageFile = () => {
	return new Promise((resolve, reject) => {
		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			success: (res) => {
				resolve(res.tempFiles[0])
			},
			fail: (err) => {
				console.log(err);
			}
		})
	})
}

export const toPage = (Opt) => {
	let url;
	if (Opt.Type == 1) {
		url = `/bizPage/docs/fileList?dirId=${Opt.dirId}&title=${Opt.title}&fileId=${Opt.fileId}&fromShare=1`
	}
	if (Opt.Type == 100 && Opt.lawFirmId) {
		url = `/lawyer/authen?lawFirmId=${Opt.lawFirmId}&fromShare=1`
	}
	uni.reLaunch({
		url
	})
}

// 预览文件
export const previewFile = async (fileUrl) => {
	const filePath = await downFile(fileUrl);
	openDocument(filePath);
}